package com.atguigu.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * className: SelectorDemo1
 * description:
 * date: 2023/3/10 0010-11:01
 * <p>
 * project: nio
 * package: com.atguigu.selector
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class SelectorDemo1 {

    public static void main(String[] args) throws IOException {
        // 创建 Selector
        Selector selector = Selector.open();

        // 通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 非阻塞
        serverSocketChannel.configureBlocking(false);

        // 绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9999));

        // 将通道注册到选择器上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 查询已经就绪的通道操作
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        // 遍历集合
        Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
        while (keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            // 判断 key 就绪状态操作
            if (key.isAcceptable()) {
                // a connection was accepted by a ServerSocketChannel
            } else if (key.isConnectable()) {
                // a connection was established with a remote server
            } else if (key.isReadable()) {
                // a channel is ready for reading
            } else if (key.isWritable()) {
                // a channel is ready for writing
            }
            keyIterator.remove();
        }
    }
}
